import { onMounted, reactive, toRef } from 'vue'
import { useRouter } from 'vue-router'
import { Toast } from 'vant'
import api from '@/api'
import globalVariables from '@/utils/globalVariables'

export default function useLogic() {
  const router = useRouter()

  const hadDeclarePopupVisibleValue = Boolean(
    sessionStorage.getItem('hadDeclarePopupVisibleValue')
  )

  const data = reactive({
    isLoginPopupVisble: false,
    isDeclarePopupVisible: !hadDeclarePopupVisibleValue,
    mobile: null,
    verifyCode: ""
  })

  const onScanStandard = () => {
    const user = localStorage.getItem('userInfo')
    if (!user) {
      data.isLoginPopupVisble = true
    } else {
      router.push({ path: '/standard' })
    }
  }

  const onLogin = async () => {
    // router.push({ path: '/orderDetails' })
    if (!data.mobile) {
      Toast('请输入银行预留手机号')
      return
    }
    if (!data.verifyCode) {
      Toast('请输入验证码')
      return
    }
    if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(data.mobile)) {
      Toast('请填写正确的手机号码')
      return
    }
    if (data.verifyCode.toString().length !== 4) {
      Toast('请输入正确位数的验证码')
      return
    }

    const res = await api.login({
      mobile: btoa(data.mobile),
      code: btoa(data.verifyCode)
    })
    if (res.error) {
      Toast(res.error.message)
      return
    }
    const { token, customerID, userCode } = res.data
    globalVariables.setUserInfo({
      token,
      customerID,
      userCode
    })
    router.push({ path: '/standard' })
  }

  const onMobileInput = e => {
    if (e.target.value.length > 11)
      data.mobile = data.mobile.toString().slice(0, 11)
  }

  const onVerifyCodeInput = e => {
    if (e.target.value.length > 4)
      data.verifyCode = e.target.value.slice(0, 4)
  }

  const onApply = () => {
    const url = 'https://apply.mcard.boc.cn/apply/NJVVZ3'
    window.location.href = url
  }

  const onConfrimDeclare = () => {
    data.isDeclarePopupVisible = false
    sessionStorage.setItem('hadDeclarePopupVisibleValue', 'true')
  }

  onMounted(() => {
    document.title = '白金卡权益领取'
  })

  return {
    isLoginPopupVisble: toRef(data, 'isLoginPopupVisble'),
    isDeclarePopupVisible: toRef(data, 'isDeclarePopupVisible'),
    mobile: toRef(data, 'mobile'),
    verifyCode: toRef(data, 'verifyCode'),
    onMobileInput,
    onVerifyCodeInput,
    onScanStandard,
    onApply,
    onLogin,
    onConfrimDeclare
  }
}
